<template>
  <div class="create-post-page">
    <h4>新建文章</h4>
    <uploader
      action="/upload"
      :beforeUpload="uploadCheck"
      @file-uploaded="handleFileUpload"
      class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
    >
      <h2>点击上传头图</h2>
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary" role="status"></div>
          <h2>正在上传</h2>
        </div>
      </template>
      <template #uploaded="dataProps">
        <img :src="dataProps.uploadedData.data.url" alt="..." />
      </template>
    </uploader>
    <validate-form @form-submit="onFormSubmit">
      <div class="mb-3">
        <label for="exampleInputEmail1" class="form-label">文章标题</label>
        <validate-input
          :rules="titleRules"
          v-model="titleVal"
          placeholder="请输入文章标题"
          type="text"
        ></validate-input>
        <div class="form-text" v-if="emailRef.error">
          {{ emailRef.message }}
        </div>
      </div>
      <div class="mb-3">
        <label for="exampleInputPassword1" class="form-label">文章详情</label>
        <validate-input
          :rules="contentRules"
          v-model="contentVal"
          placeholder="请输入文章详情"
          type="text"
          tag="textarea"
          rows="10"
        ></validate-input>
      </div>
      <template #submit>
        <span class="btn btn-primary btn-large">发表文章</span>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { GlobalDataProps, PostProps, ResponseType, ImageProps } from "../store";
import ValidateInput, { RulesProp } from "../components/ValidateInput.vue";
import ValidateForm from "../components/ValidateForm.vue";
import Uploader from "@/components/Uploader.vue";
import { beforeUploadCheck } from "../helper";
import createMessage from "@/components/createMessage";
const emailReg = /^([a-zA-Z]|[0-9])(\w|)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
export default defineComponent({
  components: {
    ValidateInput,
    ValidateForm,
    Uploader,
  },
  setup() {
    const router = useRouter();
    const store = useStore<GlobalDataProps>();

    const titleVal = ref("");
    const titleRules: RulesProp = [
      { type: "require", message: "标题不能为空" },
    ];

    const contentVal = ref("");
    const contentRules: RulesProp = [
      { type: "require", message: "内容不能为空" },
    ];

    let imageId = "";
    const handleFileUpload = (rawData: ResponseType<ImageProps>) => {
      if (rawData.data._id) {
        imageId = rawData.data._id;
      }
    };

    const onFormSubmit = (result: boolean) => {
      if (result) {
        const { column, _id } = store.state.user;
        if (column) {
          const newPost: PostProps = {
            title: titleVal.value,
            content: contentVal.value,
            column,
            author: _id,
          };
          if (imageId) {
            newPost.image = imageId;
          }
          store.dispatch("createPost", newPost).then(() => {
            createMessage("发表成功 2秒后跳转到文章", "success", 2000);
            setTimeout(() => {
              router.push({ name: "column", params: { id: column } });
            }, 2000);
          });
        }
      }
    };

    const emailRef = reactive({
      val: "",
      error: false,
      message: "",
    });

    const validataEmail = () => {
      if (emailRef.val.trim() === "") {
        emailRef.error = true;
        emailRef.message = "can not be empty";
      } else if (!emailReg.test(emailRef.val)) {
        emailRef.error = true;
        emailRef.message = "Should be vald emil";
      } else {
        emailRef.error = false;
      }
    };

    // const beforeUpload = (file: File) => {
    //   const isJPG = file.type === "image/png";
    //   if (!isJPG) {
    //     createMessage("上传图片只能是 PNG 格式!", "error");
    //   }
    //   return isJPG;
    // };

    // const onFileUploaded = (rawData: ResponseType<ImageProps>) => {
    //   createMessage(`上传成功图片ID ${rawData.data._id}`, "success");
    // };

    // const onFileUploadedError = (rawData: ResponseType<ImageProps>) => {
    //   console.log(rawData.msg);
    //   createMessage(`上传失败 ${rawData.msg}`, "error");
    // };

    const uploadCheck = (file: File) => {
      const result = beforeUploadCheck(file, {
        format: ["image/jpeg", "image/png"],
        size: 1,
      });
      const { passed, error } = result;
      if (error === "format") {
        createMessage("上传图片只能是 JPG/PNG 格式！", "error");
      }
      if (error === "size") {
        createMessage("上传图片大小 不能超过1Mb！", "error");
      }
      return passed;
    };

    return {
      emailRef,
      validataEmail,
      titleRules,
      titleVal,
      contentVal,
      contentRules,
      onFormSubmit,
      uploadCheck,
      handleFileUpload,
    };
  },
});
</script>

<style>
.create-post-page .file-upload-container {
  height: 200px;
  cursor: pointer;
}

.create-post-page .file-upload-container img {
  widows: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
